package com.xtpt.disaster.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xtpt.disaster.bean.JobDetail;
import com.xtpt.disaster.bean.JobDetailExample;
import com.xtpt.disaster.bean.NodeInfo;
import com.xtpt.disaster.common.PortalResult;
import com.xtpt.disaster.common.PortalResultPage;
import com.xtpt.disaster.mapper.JobDetailMapper;
import com.xtpt.disaster.service.JobDetailService;
import com.xtpt.disaster.service.NodeInfoManageService;
import com.xtpt.disaster.utils.IDGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class JobDetailServiceImpl implements JobDetailService {

    @Autowired
    private JobDetailMapper jobDetailMapper;

    @Autowired
    private NodeInfoManageService nodeInfoManageService;

    /**
     * @Author jack xin
     * @Method Name insert
     * @Desc 进行作业的新增，新增前进行数据校验，校验：备份类型dataType，作业状态jobStatus，执行类型jobType，备份任务ID，是否为null。
     * @Param [jobDetail]
     * @return com.xtpt.disaster.common.PortalResult
     * @Date 11:19 2021/12/2
    **/
    @Override
    public PortalResult insert(JobDetail jobDetail) {
        PortalResult validate = this.validate(jobDetail,null,0);
        if(!validate.isOK()){
            return validate;
        }
        if(jobDetail.getJobId()==null) {
            Long jobId = IDGenerator.longid();
            jobDetail.setJobId(jobId);
        }
        Integer count = jobDetailMapper.insert(jobDetail);
        return executeResult(count,"作业新增失败");
    }

    /**
     * @Author jack xin
     * @Method Name insertSelective
     * @Desc selective中，为空的值不会写入到数据库，不为空的值才写入
     * @Param [jobDetail]
     * @return com.xtpt.disaster.common.PortalResult
     * @Date 11:23 2021/12/2
    **/
    @Override
    public PortalResult insertSelective(JobDetail jobDetail) {

        PortalResult validate = this.validate(jobDetail,null,0);
        if(!validate.isOK()){
            return validate;
        }
        if(jobDetail.getJobId()==null) {
            Long jobId = IDGenerator.longid();
            jobDetail.setJobId(jobId);
        }
        Integer count = jobDetailMapper.insertSelective(jobDetail);
        return executeResult(count,"作业新增失败");
    }

    @Override
    public PortalResult update(JobDetail jobDetail) {

        PortalResult validate = this.validate(jobDetail,null,1);
        if(!validate.isOK()){
            return validate;
        }
        Integer count = jobDetailMapper.updateByPrimaryKeySelective(jobDetail);
        return executeResult(count,"作业更新失败");
    }

    @Override
    public PortalResult delete(Long jobId) {

        PortalResult validate = this.validate(null,jobId,2);
        if(!validate.isOK()){
            return validate;
        }
        Integer count = jobDetailMapper.deleteByPrimaryKey(jobId);
        return executeResult(count,"作业删除失败");
    }

    @Override
    public List<JobDetail> getJobs(JobDetail jobDetail) {
        return this.selectList(jobDetail);
    }

    /**
     * 根据条件查询列表，分页显示
     * @param jobDetail
     * @param pageNo
     * @param pageSize
     * @return PortalResultPage
     */
    @Override
    public PortalResultPage getJobsPage(JobDetail jobDetail, Integer pageNo, Integer pageSize) {
        List<JobDetail> list =  this.selectList(jobDetail);
        PageHelper.startPage(pageNo,pageSize);
        PageInfo<JobDetail> pageInfo = new PageInfo<>(list);
        return new PortalResultPage(pageInfo.getTotal(),list);
    }

    @Override
    public JobDetail getById(Long jobId) {
        return jobDetailMapper.selectByPrimaryKey(jobId);
    }

    @Override
    public JobDetail getByClientPath(Long nodeId,String clientFolderPath) {
        return jobDetailMapper.selectByClientPath(nodeId, clientFolderPath);
    }

    @Override
    public List<JobDetail> getAll() {
        return jobDetailMapper.selectAllJobDetail();
    }

    @Override
    public PortalResult deleteBatch(long[] ids) {
        int res = jobDetailMapper.deleteBatch(ids);
        if (res == 0) return PortalResult.error("删除失败");
        else return PortalResult.ok("成功删除" + res + "行数据");
    }

    @Override
    public Integer updateByPrimaryKeySelective(JobDetail jobDetail) {
        return jobDetailMapper.updateByPrimaryKeySelective(jobDetail);
    }

    @Override
    public List<Map<String, Object>> selectCountByDay(JobDetail jobDetail) {
        return jobDetailMapper.selectCountByDay(jobDetail.getJobStartTime(), jobDetail.getJobEndTime());
    }


    /**
     * 数据校验
     * @param jobDetail
     * @param action 0-insert  1-update  2-delete
     * @return
     */
    private PortalResult validate(JobDetail jobDetail,Long jobId, Integer action){

        if(0==action || 1==action){ // 新增 or 修改
            if (StringUtils.isEmpty(jobDetail.getDataType())){
                return PortalResult.error("数据类型dataType不能为空");
            }
            if (StringUtils.isEmpty(jobDetail.getTaskId())){
                return PortalResult.error("备份任务ID不能为空");
            }
            if (StringUtils.isEmpty(jobDetail.getJobType())){
                return PortalResult.error("任务类型jobType不能为空");
            }


            if( 0 == action){
                if(jobDetail.getJobId()==null)
                {
                    jobDetail.setJobId(IDGenerator.longid());
                }
                return PortalResult.ok();
            }else {
                if (StringUtils.isEmpty(jobDetail.getJobId())){
                    return PortalResult.error("作业修改jobId不能为空");
                }
            }
        }else {  // 删除
            if(StringUtils.isEmpty(jobId)){
                return PortalResult.error("作业删除jobId不能为空");
            }
        }
        return  PortalResult.ok();
    }

    private PortalResult executeResult(Integer result,String errorMsg){
        if(result > 0){
            return PortalResult.ok();
        }
        return PortalResult.error(errorMsg);
    }

    /**
     * 根据条件查询作业列表，条件参数值封装在 JobDetail对象中
     * @param jobDetail
     * @return
     */
    @Override
    public List<JobDetail> selectList(JobDetail jobDetail){

        JobDetailExample jobDetailExample = new JobDetailExample();
        JobDetailExample.Criteria criteria = jobDetailExample.createCriteria();
        if (jobDetail!=null){
            if(!StringUtils.isEmpty(jobDetail.getJobId())){
                criteria.andJobIdEqualTo(jobDetail.getJobId());
            }
            if(!StringUtils.isEmpty(jobDetail.getTaskId())){
                criteria.andTaskIdEqualTo(jobDetail.getTaskId());
            }
            if(!StringUtils.isEmpty(jobDetail.getDataType())){
                criteria.andDataTypeEqualTo(jobDetail.getDataType());
            }
            if(!StringUtils.isEmpty(jobDetail.getJobType())){
                criteria.andJobTypeEqualTo(jobDetail.getJobType());
            }
            if(!StringUtils.isEmpty(jobDetail.getJobName())){
                criteria.andJobNameEqualTo(jobDetail.getJobName());
            }
            if(!StringUtils.isEmpty(jobDetail.getSourceDbType())) {
                criteria.andSourceDbTypeEqualTo(jobDetail.getSourceDbType());
            }
            if(!StringUtils.isEmpty(jobDetail.getJobStatus())) {
                criteria.andJobStatusEqualTo(jobDetail.getJobStatus());
            }

            if(!StringUtils.isEmpty(jobDetail.getJobStartTime())){
                criteria.andJobStartTimeGreaterThanOrEqualTo(jobDetail.getJobStartTime());
            }
            if(!StringUtils.isEmpty(jobDetail.getJobEndTime())){
                criteria.andJobEndTimeLessThanOrEqualTo(jobDetail.getJobEndTime());
            }
            if(!StringUtils.isEmpty(jobDetail.getJobBackupType())){
                criteria.andJobBackupTypeEqualTo(jobDetail.getJobBackupType());
            }
        }

        //默认按开始时间倒序排列
        jobDetailExample.setOrderByClause("job_start_time desc");
        List<JobDetail> jobDetails = jobDetailMapper.selectByExample(jobDetailExample);
        return jobDetails;
    }


}
